package com.rmi.discovery;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;

/**
 * @author Dmitry
 */
public class JsonRmiDiscoveryServer extends Thread {
    DatagramSocket socket;
    private final int port;

    public JsonRmiDiscoveryServer(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        try {
            //Keep a socket open to listen to all the UDP trafic that is destined for this port
            socket = new DatagramSocket(port, InetAddress.getByName("0.0.0.0"));
            socket.setBroadcast(true);

            while (true) {
                //  System.out.println(getClass().getName() + ">>>Ready to receive broadcast packets!");
                //Receive a packet
                byte[] recvBuf = new byte[15000];
                DatagramPacket packet = new DatagramPacket(recvBuf, recvBuf.length);
                try {
                    socket.receive(packet);
                } catch (SocketException socketException) {
                    if (socket.isClosed()) {
                        return;
                    }
                }
                //Packet received
                //  System.out.println(getClass().getName() + ">>>Discovery packet received from: " + packet.getAddress().getHostAddress());
                //  System.out.println(getClass().getName() + ">>>Packet received; data: " + new String(packet.getData()));

                //See if the packet holds the right command (message)
                String message = new String(packet.getData()).trim();
                if (message.startsWith("DISCOVER_FUIFSERVER_REQUEST")) {
                    String uuid = getIdFromMessage(message);
                    if (uuid != null) {
                        if (!uuid.equals(JsonRmiFinder.jsonRmiId)) {
                            byte[] sendData = "DISCOVER_FUIFSERVER_RESPONSE".getBytes();
                            //Send a response
                            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, packet.getAddress(), packet.getPort());
                            socket.send(sendPacket);
                            //   System.out.println(getClass().getName() + ">>>Sent packet to: " + sendPacket.getAddress().getHostAddress());
                        }
                    }
                }
            }
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    private String getIdFromMessage(String message) {
        int index = message.indexOf('|');
        if (index == -1) {
            return null;
        }
        return message.substring(index + 1);
    }

    public void shutdown() {
        socket.close();
    }
}
